package com.cn.jinl.controller;

import com.alibaba.fastjson.JSONObject;
import com.cn.jinl.api.ILoginService;
import com.cn.jinl.api.ITerminalAccessService;
import com.cn.jinl.domain.Login;
import com.cn.jinl.domain.Order;
import com.cn.jinl.domain.TerminalAccess;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.JsonResponse;
import com.cn.jinl.utils.MD5Util;
import com.cn.jinl.utils.QueryForm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * @类名:LoginController
 * @包名:com.cn.jinl.controller
 * @作者:chenxingliang
 * @时间:2022-11-13 09:17
 * @版本:1.0.0
 */

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private ILoginService loginService;

    @Autowired
    HttpServletRequest httpServletRequest;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private ITerminalAccessService terminalAccessService;

    @ResponseBody
    @RequestMapping("/getLoginList/{frontToken}")
    public JsonResponse<List<Login>> getLoginList(QueryForm queryForm,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> loginResult = loginService.getLoginList(queryForm);
        response.setResult(loginResult);
        response.setSuccess(true);
        return response;
    }

    @ResponseBody
    @RequestMapping("/getLoginSelectList/{frontToken}")
    public JsonResponse<List<Login>> getLoginSelectList(@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> loginResult = loginService.getLoginSelectList();
        response.setResult(loginResult);
        response.setSuccess(true);
        return response;
    }

    @ResponseBody
    @RequestMapping("/getLoginAndRoleSelectList/{frontToken}")
    public JsonResponse<List<Login>> getLoginAndRoleSelectList(@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> loginResult = loginService.getLoginAndRoleSelectList();
        response.setResult(loginResult);
        response.setSuccess(true);
        return response;
    }

    @ResponseBody
    @RequestMapping("/getLoginAndDeptSelectList/{frontToken}")
    public JsonResponse<Map<String,List<Login>>> getLoginAndDeptSelectList(@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<Map<String,List<Login>>> response = new JsonResponse<Map<String,List<Login>>>();
        Map<String,List<Login>> loginResult = loginService.getLoginAndDeptSelectList();
        response.setResult(loginResult);
        response.setSuccess(true);
        return response;
    }

    @ResponseBody
    @RequestMapping("/addLogin/{frontToken}")
    public JsonResponse<String> addLogin(Login login,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.addLoginDetail(login);
        return CommonUtil.getResponseData(response,result);
    }

    @ResponseBody
    @RequestMapping("/updateLogin/{frontToken}")
    public JsonResponse<String> updateLogin(Login login,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.updateLoginDetail(login);
        return CommonUtil.getResponseData(response,result);
    }

    @ResponseBody
    @RequestMapping("/delLogin/{frontToken}")
    public JsonResponse<String> delLogin(@RequestBody QueryForm queryForm, @PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.delLoginDetail(queryForm);
        return CommonUtil.getResponseData(response,result);
    }

    @ResponseBody
    @RequestMapping("/updatePassword/{frontToken}")
    public JsonResponse<String> updatePassword(Login login,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.updatePassword(login);
        return CommonUtil.getResponseData(response,result);
    }


    @ResponseBody
    @RequestMapping("/doLogin")
    public JsonResponse<Login> doLogin(Login login) throws Exception {
        JsonResponse<Login> response = new JsonResponse<Login>();
        Login result = loginService.doLogin(login);
        response.setSuccess(StringUtils.isEmpty(result.getMessage())?true:false);
        response.setResult(result);
        return response;
    }


    @ResponseBody
    @RequestMapping("/getLoginDetail/{frontToken}")
    public JsonResponse<String> getLoginDetail(Login login,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.getLoginDetail(login);
        return CommonUtil.getResponseData(response,result);
    }

    @ResponseBody
    @RequestMapping("/loginOut")
    public JsonResponse<String> loginOut(HttpServletRequest httpServletRequest) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String sessionId = httpServletRequest.getSession().getId();
        redisTemplate.delete(sessionId);
        response.setSuccess(true);
        return response;
    }

    /**
     * 更新token
     */

    @ResponseBody
    @RequestMapping("/getRefreshToken")
    public JsonResponse<Login> getRefreshToken() throws Exception {
        JsonResponse<Login> response = new JsonResponse<Login>();
        String sessionId = httpServletRequest.getSession().getId();
        String token = (String) redisTemplate.opsForValue().get(sessionId);
        Login login = new Login();
        login.setToken(token);
        JSONObject jsonObject = JSONObject.parseObject(MD5Util.getDecoder(token));
        login.setId(jsonObject.getString("id"));
        login.setUserAccount(jsonObject.getString("userAccount"));
        login.setUserName(jsonObject.getString("userName"));
        login.setAccountType(jsonObject.getString("accountType"));
        response.setResult(login);
        response.setSuccess(true);
        return response;
    }

    @ResponseBody
    @RequestMapping("/api/doLoginByPhone")
    public JsonResponse<Login> doLoginByPhone(String  user, String password,String code) throws Exception {
        JsonResponse<Login> response = new JsonResponse<Login>();
        Login result = loginService.doLoginByPhone(user,password,code);
        response.setResult(result);
        response.setSuccess(StringUtils.isEmpty(result.getMessage())?true:false);
        return response;
    }

    @ResponseBody
    @RequestMapping("/api/sendCode")
    public JsonResponse<String> sendCode(@RequestParam(value = "phone", required = true) String phone) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.sendCode(phone);
        response.setResult(result);
        response.setSuccess(true);
        return response;
    }

    //获取操作工名称
    @ResponseBody
    @RequestMapping("/api/getLoginNameByWorkNum")
    public JsonResponse<String> getLoginNameByWorkNum(@RequestParam(value = "workNum", required = true) String workNum) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.getLoginNameByWorkNum(workNum);
        response.setResult(result);
        response.setSuccess(true);
        return response;
    }

    //获取料原人名称
    @ResponseBody
    @RequestMapping("/api/getLoginLiaoYuan")
    public JsonResponse<List<Login>> getLoginLiaoYuan() throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> result = loginService.getLoginLiaoYuan();
        response.setResult(result);
        response.setSuccess(true);
        return response;
    }

    //判断mac地址是否配置
    @ResponseBody
    @RequestMapping("/toGetMac")
    public JsonResponse toGetMac() throws Exception {
        JsonResponse response = new JsonResponse();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (networkInterface != null) {
                    byte[] macAddressBytes = networkInterface.getHardwareAddress();
                    if (macAddressBytes != null) {
                        StringBuilder macAddress = new StringBuilder();
                        for (int i = 0; i < macAddressBytes.length; i++) {
                            macAddress.append(String.format("%02X%s", macAddressBytes[i], (i < macAddressBytes.length - 1) ? "-" : ""));
                        }
                        List<TerminalAccess> list = terminalAccessService.getMac(macAddress.toString());
                        if (list.size() >= 1) {
                            response.setSuccess(true);
                            // 可以在这里处理查询结果
                        }
                    } else {
                        System.out.println("MAC Address not found.");
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return response;
    }

    //用户输入自匹配
    @ResponseBody
    @RequestMapping("/getNameList/{frontToken}")
    public JsonResponse<List<Login>> getNameList(@RequestBody String queryString,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> loginResult = loginService.getNameList(queryString);
        response.setResult(loginResult);
        response.setSuccess(true);
        return response;
    }


    //获取报修班组人员信息
    @ResponseBody
    @RequestMapping("/getRepairPersonList/{frontToken}")
    public JsonResponse<List<Login>> getRepairPersonList(@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> loginResult = loginService.getRepairPersonList();
        response.setResult(loginResult);
        response.setSuccess(true);
        return response;
    }


    //app获取报修班组人员信息
    @ResponseBody
    @RequestMapping("/getRepairPersonListApp")
    public JsonResponse<List<Login>> getRepairPersonListApp() throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> loginResult = loginService.getRepairPersonList();
        response.setResult(loginResult);
        response.setSuccess(true);
        return response;
    }
}
